package com.excel.util;



import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
@Slf4j
public class TransactionUtils {
    //PlatformTransactionManager是Spring框架中用于管理事务的接口。它提供了开启、提交、回滚和验证事务状态等方法
    private final PlatformTransactionManager transactionManager;

 
    public TransactionUtils(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }


 
    public void runInTransaction(TransactionalTask task){
        //DefaultTransactionDefinition是Spring框架中的一个默认事务定义类。它实现了//TransactionDefinition接口，提供了一些常用的事务属性和默认值。
        //在示例代码中，我们使用DefaultTransactionDefinition来创建一个新的事务定义对象，以便开启新的事务并获取对应的事务状态。
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            task.run();
            transactionManager.commit(status);
        }catch (Exception e) {
            transactionManager.rollback(status);
            log.error("导入事务执行失败",e);
            throw new CorpBusinessException(OrganizationResponseCodeEnum.IMPORT_EXCEL_ERROR);
        }
    }
}
